import React, { Component, Fragment } from 'react'
import { createForm } from 'rc-form'
import { Toast, Picker, DatePicker } from 'antd-mobile'
import schema from 'async-validator'
import moment from 'moment'

import getUrlParams from '../js/getUrlParams'

import { getProvince, getProvinceByCity, getInsititution, sendCode, receiveCourse } from '../api'

const descriptor = {
    city: {
        required: true,
        message: '所在城市不能为空！'
    },
    school: {
        required: true,
        message: '体验校区不能为空！'
    },
    fullname: [
        {
            required: true,
            message: '宝宝名字不能为空！'
        },
        {
            max: 10,
            message: '宝宝名字太长啦！'
        }
    ],
    gender: {
        required: true,
        message: '性别不能为空！'
    },
    birthday: {
        required: true,
        message: '年龄不能为空！'
    },
    phone: [
        {
            required: true,
            message: '手机号不能为空！'
        },
        {
            pattern: /^1[3-9]\d{9}$/,
            message: '手机号格式错误！'
        }
    ],
    code: {
        required: true,
        message: '验证码不能为空！'
    }
}

schema.warning = () => {}

const validator = new schema(descriptor)

const CustomChildren = props => {
    let opacity = 1

    switch (props.extra) {
        case '所在城市':
        case '体验校区':
        case '性别':
        case '年龄':
        opacity = .25
    }

    return <div style={{width: props.width}} className="input" onClick={props.onClick}>
        <div>{ props.children }</div>
        <div style={{opacity}}>{ props.extra }</div>
    </div>
}

class Form extends Component {
    constructor() {
        super()
        this.state = {
            cascadeCity: [],
            cityValue: [],
            insititution: [],
            countNum: 120,
            isCountDown: false,
            gender: [
                {label: '男', value: 1},
                {label: '女', value: 2}
            ],
            state: 1
        }
        this.getProvinceByCity = this.getProvinceByCity.bind(this)
    }

    getProvince = async () => {
        this.setState({
            cityValue: this.props.form.getFieldValue('city')
        })

        if (this.state.cascadeCity.length) return

        const { data } = await getProvince()

        this.setState({
            cascadeCity: data.map(item => ({
                label: item.ProvinceName,
                value: item.ProvinceId
            }))
        }, () => {
            this.getProvinceByCity([this.state.cascadeCity[0].value])
        })
    }

    getProvinceByCity = async val => {
        const { cascadeCity } = this.state

        for (let i = 0; i < cascadeCity.length; i++) {
            if (cascadeCity[i].value === val[0] && !cascadeCity[i].children) {
                const { data } = await getProvinceByCity({provinceId: val[0]})

                cascadeCity[i].children = data.map(item => ({
                    label: item.CityName,
                    value: item.CityId
                }))

                if (val.length === 1 && cascadeCity[i].children.length) {
                    val.push(cascadeCity[i].children[0].value)
                }

                break
            }
        }

        this.setState({
            cascadeCity,
            cityValue: val
        })
    }

    setCity = () => {
        const oldCity = this.props.form.getFieldValue('city')
        const newCity = this.state.cityValue

        if (oldCity && oldCity.toString() === newCity.toString()) return

        this.props.form.setFieldsValue({
            city: newCity,
            school: []
        })

        this.getInsititution(...newCity)
    }

    getInsititution = async (provinceId, cityId) => {
        const { data } = await getInsititution({ provinceId, cityId })

        this.setState({
            insititution: data.map(item => ({
                label: item.value,
                value: item.key
            }))
        })
    }

    sendCode = async () => {
        let timer = null
        const phone = this.props.form.getFieldValue('phone')

        if (phone === '' || phone === undefined) {
            Toast.info('手机号不能为空！', 2, null, false)
            return
        }

        if (!(/^1[3-9]\d{9}$/.test(phone))) {
            Toast.info('手机号格式错误！', 2, null, false)
            return
        }

        const { code, message } = await sendCode({
            mobile: phone
        })

        Toast.info(message, 2, null, false)

        if (code === 1) {
            this.setState({
                isCountDown: true
            })

            timer = setInterval(() => {
                this.setState({
                    countNum: this.state.countNum -= 1
                }, () => {
                    if (this.state.countNum === 0) {
                        this.setState({
                            isCountDown: false,
                            countNum: 120
                        })
        
                        clearInterval(timer)
                    }
                })
            }, 1000)
        }
    }

    handleSubmit = () => {
        this.props.form.validateFields((error, values) => {
            validator.validate(values, async errors => {
                if (errors) {
                    Toast.info(errors[0].message, 2, null, false)

                    return
                }

                const { code, message } = await receiveCourse({
                    StudentId: getUrlParams('studentId'),
                    ReadPictureBookId: getUrlParams('pictureBookId'),
                    CustomerCollectInstitutionId: values.school[0],
                    CustomerCollectName: values.fullname,
                    CustomerCollectSex: values.gender[0],
                    CustomerCollectBirthday: moment(values.birthday).format('YYYY-MM-DD'),
                    CustomerCollectMobile: values.phone,
                    Vcode: values.code
                })

                if (code === 1) {
                    this.setState({
                        state: 2
                    })
                } else if (code === 8) {
                    this.setState({
                        state: 3
                    })
                } else {
                    Toast.info(message, 2, null, false)
                }
            })
        })
    }

    render() {
        const { getFieldProps } = this.props.form
        const { gender, cascadeCity, cityValue, insititution, countNum, isCountDown, state } = this.state

        return (
            <Fragment>
                <form style={{display: state === 1 ? '' : 'none'}}>
                    <div className="form-group">
                        <Picker
                            data={cascadeCity}
                            extra="所在城市"
                            {...getFieldProps('city')}
                        >
                            <CustomChildren width="2.2rem"/>
                        </Picker>
                        <Picker
                            data={cascadeCity}
                            onVisibleChange={this.getProvince}
                            onPickerChange={this.getProvinceByCity}
                            onOk={this.setCity}
                            value={cityValue}
                            cols={2}
                        >
                            <CustomChildren width="2.2rem"/>
                        </Picker>
                        <Picker
                            data={insititution} 
                            extra="体验校区" 
                            cols={1} 
                            {...getFieldProps('school')}
                        >
                            <CustomChildren width="3.5rem"/>
                        </Picker>
                    </div>
                    <div className="form-group">
                        <input placeholder="宝宝名字" {...getFieldProps('fullname', {
                            getValueFromEvent: event => event.target.value.trim()
                        })}/>
                    </div>
                    <div className="form-group">
                        <Picker data={gender} extra="性别" cols={1} {...getFieldProps('gender')}>
                            <CustomChildren width="2.2rem"/>
                        </Picker>
                        <DatePicker mode="date" extra="年龄" {...getFieldProps('birthday')}>
                            <CustomChildren width="3.5rem"/>
                        </DatePicker>
                    </div>
                    <div className="form-group">
                    <input placeholder="手机号" {...getFieldProps('phone', {
                        getValueFromEvent: event => event.target.value.trim()
                    })}/>
                    </div>
                    <div className="form-group">
                        <input style={{width: '3.1rem'}} placeholder="短信验证码" {...getFieldProps('code', {
                            getValueFromEvent: event => event.target.value.trim()
                        })}/>
                        {
                            isCountDown
                            ?
                            <a>{countNum} s</a>
                            :
                            <a onClick={this.sendCode}>获取验证码</a>
                        }
                    </div>
                    <a className="free-collection" onClick={this.handleSubmit}></a>
                </form>
                <div className="success" style={{display: state === 2 ? '' : 'none'}}>
                    <img src={require('../images/success_icon.png')} alt=""/>
                    <p>领取成功</p>
                    <p>老师会及时与您联系，请耐心等待</p>
                </div>
                <div className="applied" style={{display: state === 3 ? '' : 'none'}}>
                    <p>您的号码已经申请，该福利只有新用户才能领取</p>
                </div>
            </Fragment>
        )
    }
}

export default createForm()(Form)